﻿/*
 * Catalyst - http://catalystobjects.com
 * 
 * New BSD License (BSD)
 * 
 * Copyright (c) 2009, Ashley Brener
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Midlet Earth nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Catalyst.Xml.Serialization;

namespace Catalyst
{
	

	public abstract class BusinessObject<ItemType> : IXmlSerializable
		where ItemType : BusinessObject<ItemType>, new()
	{
		#region IXmlSerializable Members

		public new XmlSchema GetSchema()
		{
			return null;
		}

		public void ReadXml(XmlReader reader)
		{
			XmlSerializer<ItemType>.Deserialize(reader, (ItemType)this);
		}

		public void WriteXml(XmlWriter writer)
		{
			XmlSerializer<ItemType>.Serialize(writer, (ItemType)this);
		}

		#endregion

	//    public class DataRequest
	//    {
	//        public DataRequest(string DatabaseName, string ConnectionString, string TableName, IRepository<T> Repo)
	//            : this(DatabaseName, ConnectionString, TableName, Repo, null)
	//        {
			
	//        }

	//        public DataRequest(string DatabaseName, string ConnectionString, string TableName, IRepository<T> Repo, Expression<Func<T, bool>> Expression)
	//        {
	//            this.DatabaseName = DatabaseName;
	//            this.ConnectionString = ConnectionString;
	//            this.TableName = TableName;
	//            this.Repo = Repo;
	//            this.Expression = Expression;
	//        }

	//        public string DatabaseName { get; set; }
	//        public string ConnectionString { get; set; }
	//        public string TableName { get; set; }
	//        public IRepository<T> Repo { get; set; }
	//        public Expression<Func<T, bool>> Expression { get; set; }
	//    }

	//    private static string getCacheKey(DataRequest dataRequest)
	//    {
	//        return String.Format("{0}_{1}{2}", dataRequest.DatabaseName, dataRequest.TableName, (dataRequest.Expression != null) ? String.Format("({0})", dataRequest.Expression) : "");
	//    }

	//    public static List<T> GetCachedData(DataRequest DataRequest)
	//    {
	//        if (checkIfCachedTable(DataRequest))
	//        {
	//            List<T> allItems = CachingService.GetCachedObject<List<T>, DataRequest>(CachedDataLoader<T>.getCacheKey(DataRequest), new CachingService.ObjectLoader<List<T>, DataRequest>(CachedDataLoader<T>.getAllCachedData), new DataRequest[] { DataRequest });

	//            return Cloning.CloneHelper<List<T>>.Clone(allItems);
	//        }

	//        return getFreshData(DataRequest);
	//    }

	//    private static CacheSettings<List<T>> getAllCachedData(params DataRequest[] dataRequests)
	//    {
	//        DataRequest dataRequest = dataRequests[0];

	//        CacheSettings<List<T>> settings = new CacheSettings<List<T>>();

	//        SqlCacheDependency dependency = null;

	//        if (checkIfCachedTable(dataRequest))
	//        {
	//            dependency = new SqlCacheDependency(dataRequest.DatabaseName, dataRequest.TableName);
	//        }

	//        settings.CachedObject = getFreshData(dataRequest);
	//        settings.Dependency = dependency;

	//        return settings;
	//    }

	//    private static List<T> getFreshData(DataRequest dataRequest)
	//    {
	//        if (dataRequest.Expression != null)
	//        {
	//            return dataRequest.Repo.GetAll().Where(dataRequest.Expression).ToList();
	//        }

	//        return dataRequest.Repo.GetAll().ToList();
	//    }

	//    private static bool checkIfCachedTable(DataRequest dataRequest)
	//    {
	//        //if (HttpContext.Current != null)
	//        //{
	//            foreach (string enabledTable in SqlCacheHelper.GetTablesEnabledForSqlCacheDependency(dataRequest.ConnectionString))
	//            {
	//                if (enabledTable == dataRequest.TableName)
	//                {
	//                    return true;
	//                }
	//            }
	//        //}

	//        return false;
	//    }
	//}

	//public static class SqlCacheHelper
	//{
	//    private const string triggerSuffix = "_AspNet_SqlCacheNotification_Trigger";

	//    private static List<string> notificationTables;

	//    public static List<string> GetTablesEnabledForSqlCacheDependency(string ConnectionString)
	//    {
	//        if (notificationTables == null)
	//        {
	//            notificationTables = new List<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(ConnectionString));

	//            const string triggerSuffix = "_AspNet_SqlCacheNotification_Trigger";

	//            List<string> triggers = new List<string>();

	//            IDataReader reader = new Select("name")
	//            .From("sysobjects")
	//            .Where("xtype").IsEqualTo("TR")
	//            .And("name").Like("%" + triggerSuffix)
	//            .ExecuteReader();

	//            while (reader.Read())
	//            {
	//                triggers.Add(reader["name"].ToString());
	//            }

	//            reader.Close();

	//            // Re-enable SqlCacheDependency if no trigger exists on table
	//            foreach (string tableName in notificationTables)
	//            {
	//                if (!triggers.Contains(tableName + triggerSuffix))
	//                {
	//                    SqlCacheDependencyAdmin.EnableTableForNotifications(ConnectionString, tableName);
	//                }
	//            }

	//            // Disable SqlCacheDependency if table removed from AspNet_SqlCacheTablesForChangeNotification table
	//            foreach (string trigger in triggers)
	//            {
	//                string tableName = trigger.Replace(triggerSuffix, "");

	//                if (!notificationTables.Contains(tableName))
	//                {
	//                    SqlCacheDependencyAdmin.DisableTableForNotifications(ConnectionString, tableName);
	//                }
	//            }
	//        }

	//        return notificationTables;
	//    }
	//}
	}
}
